# -*- coding: utf-8 -*-

import cgi
import sys, os
import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import facebook
from facebook import FacebookError
from google.appengine.ext import db
from funcs  import Utility, FBjqRY

version='beta 1.0'
#need to add save db.model
#2009.1103
#add set status function
#2009.1104
#g_ADDRESS='118.169.19.179'
g_ADDRESS='wolkefacebook.appspot.com'
FACEBOOK_API_KEY ='a8dfbf5416044ed379eaf8a4bb424fdf'
FACEBOOK_SECRET_KEY ='e950aa7805c18e5fa6223367810a5e3d'

_DEBUG = True

#Model
class NotiAllocationData(db.Model):
    firned_index=db.IntegerProperty(required=True)
    today_noti=db.IntegerProperty(required=True)
    update=db.DateTimeProperty(auto_now=True)

class Funcs(webapp.RequestHandler):
    def get(self):
        self.response.out.write(template.render('funcs.js',{'address':g_ADDRESS}))

class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.out.write('work')
    def post(self):
        fb = facebook.Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY)
        if fb.check_session(self.request) and fb.added:
            pass
        else:
            url = fb.get_add_url()
            self.response.out.write('<script language="javascript">top.location.href="' + url + '"</script>')
            return
        friend = fb.friends.get()
        uids = fb.users.getInfo(friend,['uid'])
        al = fb.admin.getAllocation('notifications_per_day') #Allcoation
        fi = 0 #friend index
        tc = 0 #today count
        
        try:            
            no = db.get_by_key_name(fb.uid)#user id
            fi = no.firned_index
            tc = no.today_noti
        except:
            pass        
        self.response.out.write(template.render('notification.html',{'uids':uids,'address':g_ADDRESS,'f_index':fi,
                                                                     'today_noti':tc ,'Allocation':al,'version':version}))
        
            
class Notification(webapp.RequestHandler):
    def post(self):
        fb = facebook.Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY)
        if fb.check_session(self.request) and fb.added:
            pass
        else:
            url = fb.get_add_url()
            self.response.out.write('<script language="javascript">top.location.href="' + url + '"</script>')
            return
        al=int(fb.admin.getAllocation('notifications_per_day'))
        msg=self.request.get('msg')
        f_index=self.request.get('index')
        
        friend = fb.friends.get()
        uids = fb.users.getInfo(friend,['uid'])
        to_ids=[]
        #set to_ids
        i=int(f_index)
        i_max=int(len(uids))
        if i_max > (i+al):
            i_max=(i+al)
        while i < i_max:
            to_ids.append(uids[i]['uid'])
            i=i+1            
        #send notification
        try:
            s='%s' % msg
            if fb.uid!='1733674053':
                s=s+' App By <fb:name uid="1713094070" linked="true">Wolke</a>'
                #2009.1103 REMMBER TO TEST THIS
                
            
            fb.notifications.send(to_ids,s,'user_to_user')
            #self.response.out.write('notification work %s %i / %i | %i' % (to_ids,i,i_max,al))
            info=fb.users.getInfo(to_ids,['name','pic_square'])
            self.response.out.write('<h2>Notification to :</h2><br />')
            i=0
            for i in range(len(info)):
                self.response.out.write('<img src="%s" title="%s" /> %s ,<br />' % (info[i]['pic_square'],info[i]['name'],info[i]['name']))

            #for i in range(len(to_ids)):
                #self.response.out.write()
#            %s %i / %i | %i' % (to_ids,i,i_max,al))
        except:
            self.response.out.write('error')
            return
        #record data
        #try:
        #    noti=db.get_by_key_name(fb.uid)
        #except:
            #pass
        #    noti=NotiAllocationData(key_name=fb.uid)
        #noti.firned_index=i_max
        #noti.today_noti=(i_max-i)
        #noti.put()
        
class SendMsg(webapp.RequestHandler):
    def post(self):
        fb = facebook.Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY)
        if fb.check_session(self.request) and fb.added:
            pass
        else:
            url = fb.get_add_url()
            self.response.out.write('<script language="javascript">top.location.href="' + url + '"</script>')
            return
        msg = self.request.get('status_msg')
        try:
            fb.status.set(msg)
            
            self.response.out.write('write %s on your wall' % (msg))
        except:
            self.response.out.write('error')
                        
def main():
    application = webapp.WSGIApplication([
        ('/',MainPage),
        ('/Utility.js', Utility),
        ('/FBjqRY.min.js', FBjqRY),
        ('/funcs.js', Funcs),
        ('/notification',Notification),#notification
        ('/sendMsg',SendMsg)#send Msg
        ],debug=_DEBUG)
    wsgiref.handlers.CGIHandler().run(application)
    
if __name__ == "__main__":
    main()      
